package com.fscp.oauth2.server.service;

import com.fscp.commons.model.domain.SignInIdentity;
import com.fscp.commons.model.pojo.Diner;
import com.fscp.commons.utils.AssertUtil;
import com.fscp.oauth2.server.mapper.DinerMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService implements UserDetailsService {

    @Resource
    private DinerMapper dinerMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AssertUtil.isNotEmpty(username, "请输入用户名");
        Diner diner = dinerMapper.selectByAccountInfo(username);
        if (diner == null) {
            throw new UsernameNotFoundException("用户名不存在，请重新输入");
        }
        // 初始化登录认证对象
        SignInIdentity signInIdentity = new SignInIdentity();
        // 拷贝属性
        BeanUtils.copyProperties(diner, signInIdentity);
        // return 简化； 也是解决碰到的 ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.fscp.commons.model.domain.SignInIdentity
        return signInIdentity;
        /*
        return new User(username, diner.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(diner.getRoles()));
         */
    }
}
